﻿/*
 * Calendar plugin
 * (c) 2007-2009 Igor Galeta <brainberry.ua>
 * MIT license
 *
 * Options:
 *  1. lang - 'ru', 'ua' or 'en'
 *  2. start_year - Рік з якого буде починатися список років. Параметр не обовязковий, за замовчуванням start_year рівний -5 від поточного
 *  3. Початкові параметри відповідно
 *     year: 0
 *     month: 0
 *     day: 0
 *     hour: 0
 *     minute: 0
 *  4. onSelect - callback function, call when calendar date selected. The first argument is calendar instance
 *  5. timeout - miliseconds to hide calendar
 *  6. timer - true or false, autohide calendar, when mouse out
 *  7. select_time - true or false, show time selector if true
 *  8. format - datetime format
   
 * var calendar = new Calendar('my_calendar', {lang:'ru', onSelect:selectDate, timeout:2000});
 * calendar.toggle();
 */
var CALENDAR = {};
CALENDAR.lang = {};
var Calendar = Class.create();

Calendar.prototype = {
  initialize: function(guid) 
  {
    var defaults = {
      zindex: 1000,
      left: 0,
      top: 0,
      year: 0,
      month: 0,
      day: 0,
      hour: 0,
      minute: 0,
      year_list:'c_year_list',
      year_list_prev: 'c_year_list_prev',
      year_list_next: 'c_year_list_next',
      month_list:'c_month_list',
      days_names_list: 'c_days_names_list',
      day_list_1:'c_day_list_1',
      day_list_2:'c_day_list_2',
      hour_list: 'c_hour',
      min_list: 'c_minute',
      select_link: 'c_select_link',
      hide_link: 'c_hide_link',
      time_link_prev: 'c_time_prev',
      time_link_next: 'c_time_next',
      time_link_reset: 'c_reset_time_link',
      time_table: 'time_table',
      onSelect:false,
      onHide:false,
      onShow:false,
      timeout:1000,
      timer: true,
      lang: 'ru',
      start_year: false,
      select_time: true,
      format: "%d.%m.%Y %H:%M"
      };
      
	  this.options = Object.extend(defaults, arguments[1] || {});
	
	  //current real year
	  this.cDate = new Date();
	  this.cYear = this.cDate.getFullYear();
	  this.cMonth = this.cDate.getMonth();
	  this.cDay = this.cDate.getDate();
	  this.cHour = this.cDate.getHours();
	  this.cMinute = this.cDate.getMinutes();
	
	  //selected year
	  this.sYear = (this.options.year) ? this.options.year : this.cYear;
	  this.sMonth = (this.options.month) ? this.options.month : this.cMonth;
	  this.sDay = (this.options.day) ? this.options.day : this.cDay;
	  this.sHour = (this.options.hour) ? this.options.hour : this.cHour;
	  this.sMinute = (this.options.minute) ? this.options.minute : this.cMinute;
	
	  // Keep selected date
	  this.mYear = this.sYear;
	  this.mMonth = this.sMonth;
	  this.mDay = this.sDay;
	  
	  //init current language
		this.locale = (this.options.lang) ? this.options.lang : 'ru';
	  this.language = CALENDAR.lang[this.locale];
   	this.init_language();
	  
	  //elements
	  this.element = $(guid);
	  
	  if(this.element)
	  {
	    this.element_month_list = $(this.options.month_list);
	    this.element_year_list = $(this.options.year_list);
	    this.element_day_list_1 = $(this.options.day_list_1);
	    this.element_day_list_2 = $(this.options.day_list_2);
	    this.element_days_names = $(this.options.days_names_list);
	    this.element_year_prev = $(this.options.year_list_prev);
	    this.element_year_next = $(this.options.year_list_next);
	    this.element_select_link = $(this.options.select_link);
	    this.element_hide_link = $(this.options.hide_link);
	    
	    this.element_hour = $(this.options.hour_list);
	    this.element_minute = $(this.options.min_list);
	    this.time_link_prev = $(this.options.time_link_prev);
	    this.time_link_next = $(this.options.time_link_next);
	    this.time_link_reset = $(this.options.time_link_reset);
	    this.time_table = $(this.options.time_table);
	  }
	  else
	  {
	    this.init_html(guid);
	  }

	  //events
	  Event.observe(this.element_year_prev, 'click', this.moveYearListDown.bind(this));
    Event.observe(this.element_year_next, 'click', this.moveYearListUp.bind(this));
	  Event.observe(this.element_select_link, 'click', this.select.bind(this));
	  Event.observe(this.element_hide_link, 'click', this.hide.bind(this));
	  
	  if (this.options.timer)
	  {
	    this.eventStopTimeout = this.stopTimeout.bindAsEventListener(this);
	    this.eventStartTimeout = this.startTimeout.bindAsEventListener(this);
	  
	    Event.observe(this.element, "mouseover", this.eventStopTimeout);
	    Event.observe(this.element, "mouseout", this.eventStartTimeout);
	  }
	  
	  if (this.options.select_time)
	  {
	    this.eventKeypress = this.keypress.bindAsEventListener(this);
  	  Event.observe(document, "keypress", this.eventKeypress);
	  
	    Event.observe(this.element_hour, 'click', this.setTimeModeEvent.bind(this));
	    Event.observe(this.element_minute, 'click', this.setTimeModeEvent.bind(this));
	    
	    Event.observe(this.time_link_prev, 'click', function(event){Event.stop(event)});
	    Event.observe(this.time_link_prev, 'drag', function(event){Event.stop(event)});
	    Event.observe(this.time_link_prev, 'mousedown', this.startTimerEvent.bind(this));
	    Event.observe(this.time_link_prev, 'mouseup', this.endTimer.bind(this));
	    Event.observe(this.time_link_prev, 'mouseover', this.endTimer.bind(this));
	    
	    Event.observe(this.time_link_next, 'click', function(event){Event.stop(event)});
	    Event.observe(this.time_link_next, 'drag', function(event){Event.stop(event)});
	    Event.observe(this.time_link_next, 'mousedown', this.startTimerEvent.bind(this));
	    Event.observe(this.time_link_next, 'mouseup', this.endTimer.bind(this));
	    Event.observe(this.time_link_next, 'mouseover', this.endTimer.bind(this));
	    
	    Event.observe(this.time_link_reset, 'click', this.resetTime.bind(this));
	  }
	  
	  //hide
	  this.hide();
	
	  //first year in list
	  this.fYear = (this.options.start_year) ? this.options.start_year : (this.sYear - 5);
   	
   	// calendar
	  this.initYearList(this.fYear);
	  this.initMonthList(this.sMonth);
	  this.initDaysNames();
	  this.initDate();
	  
	  if (this.options.select_time)
	  {
	    // time
	    this.time_mode = true; //inc or desc hour if true and minutes if false
	    this.time_reset = true; //reset time to 00:00 if true and 23:59 if false
	    this.initTime();
	    this.setTimeMode(1);
	  }
	  else
	  {
	    Element.hide(this.time_link_reset);
	    this.time_table.style.visibility = 'hidden';
	  }
  },
  
  // Create html table
  create_html_table: function()
  {
    var table = document.createElement('TABLE');
    table.appendChild(document.createElement("TBODY"));
    table.border = 0;
    table.setAttribute('cellspacing', 0);
    table.setAttribute('cellpadding', 0);
    
    return table;
  },
  
  // Create calendar html sceleton
  init_html: function(guid)
  {
    this.element = document.createElement('DIV');
    this.element.id = guid;
    this.element.className = "calendar";
    this.element.style.display = "none";
    
    var table = this.create_html_table();
    
    var row = table.tBodies[0].insertRow(0);
    var cell = row.insertCell(row.cells.length);
    
    this.element_days_names = this.create_html_table();
    this.element_days_names.width = "100%";
    this.element_days_names.className = "week";
    
    cell.appendChild(this.element_days_names);
    for(var i = 0; i < 2; i++)
    {
      cell = row.insertCell(row.cells.length);
      cell.innerHTML = "&nbsp;";
    }
    
    row = table.tBodies[0].insertRow(1);
    cell = row.insertCell(row.cells.length);
    cell.setAttribute("valign", "top");
    
    this.element_day_list_1 = this.create_html_table();
    rr = this.element_day_list_1.tBodies[0].insertRow(0);
    cc = rr.insertCell(0);
    cc.setAttribute("colspan", 7);
    
    cell.appendChild(this.element_day_list_1);
    
    this.element_day_list_2 = this.create_html_table();
    rr = this.element_day_list_2.tBodies[0].insertRow(0);
    cc = rr.insertCell(0);
    cc.setAttribute('colspan', 7);
    
    cell.appendChild(this.element_day_list_2);
    
    this.element_month_list = row.insertCell(row.cells.length);
    this.element_month_list.className = "scroll";
    
    cell = row.insertCell(row.cells.length);
    cell.className = "scroll";
    
    var div = document.createElement('DIV');
    this.element_year_prev = document.createElement('A');
    this.element_year_prev.href = "javascript:void(0);"
    this.element_year_prev.innerHTML = '<img src="/images/calendar/calendar_up.gif" alt="' + this.language.previous + '" border="0" />';
    div.appendChild(this.element_year_prev);
    cell.appendChild(div);
    
    this.element_year_list = document.createElement('DIV');
    cell.appendChild(this.element_year_list);
    
    var div = document.createElement('DIV');
    this.element_year_next = document.createElement('A');
    this.element_year_next.href = "javascript:void(0);"
    this.element_year_next.innerHTML = '<img src="/images/calendar/calendar_down.gif" alt="' + this.language.next + '" border="0" />';
    div.appendChild(this.element_year_next);
    cell.appendChild(div);
    
    this.element.appendChild(table);
    
    // time
    var div_time = document.createElement('DIV');
    div_time.className = "time";
    
    this.time_table = this.create_html_table();
    
    row = this.time_table.tBodies[0].insertRow(0);
    cell = row.insertCell(row.cells.length);
    cell.setAttribute('rowspan', 2);
    cell.innerHTML = this.language.time;
    cell = row.insertCell(row.cells.length);
    cell.setAttribute("rowspan", 2);
    
    table = this.create_html_table();
    table.className = "clock";
    rr = table.tBodies[0].insertRow(0);
    this.element_hour = rr.insertCell(rr.cells.length);
    this.element_hour.className = "act";
    cc = rr.insertCell(rr.cells.length);
    cc.innerHTML = ":";
    this.element_minute = rr.insertCell(rr.cells.length);
    cell.appendChild(table);
    
    cell = row.insertCell(row.cells.length);
    this.time_link_prev = document.createElement('A');
    this.time_link_prev.href = "javascript:void(0);";
    this.time_link_prev.innerHTML = '<img src="/images/calendar/calendar_up.gif" alt="' + this.language.next + '" border="0">';
    cell.appendChild(this.time_link_prev);
    
    row = this.time_table.tBodies[0].insertRow(1);
    cell = row.insertCell(row.cells.length);
    this.time_link_next = document.createElement('A');
    this.time_link_next.href = "javascript:void(0);";
    this.time_link_next.innerHTML = '<img src="/images/calendar/calendar_down.gif" alt="' + this.language.next + '" border="0"></a>';
    cell.appendChild(this.time_link_next);
    
    div_time.appendChild(this.time_table);

    var div_ok = document.createElement('DIV');
    div_ok.className = "ok";
    
    table = this.create_html_table();
    
    row = table.tBodies[0].insertRow(0);
    cell = row.insertCell(row.cells.length);
    this.element_select_link = document.createElement('A');
    this.element_select_link.href = "javascript:void(0);";
    this.element_select_link.innerHTML = this.language.apply;
    this.element_select_link.className = "select";
    cell.appendChild(this.element_select_link);
    
    this.time_link_reset = document.createElement('A');
    this.time_link_reset.href = "javascript:void(0);";
    this.time_link_reset.innerHTML = this.language.clear;
    cell.appendChild(this.time_link_reset);
    
    cell = row.insertCell(row.cells.length);
    this.element_hide_link = document.createElement('A');
    this.element_hide_link.href = "javascript:void(0);";
    this.element_hide_link.innerHTML = '<img src="/images/calendar/calendar_cancel.gif" alt="' + this.language.cancel + '" border="0">';
    cell.appendChild(this.element_hide_link);
    
    div_ok.appendChild(table);
    div_time.appendChild(div_ok);
    
    this.element.appendChild(div_time);
    
    document.body.appendChild(this.element);
  },
  
  // Define variables by language
  init_language: function()
  {
    //this.arrMonth = Date.CultureInfo.monthNames.slice();
    //this.arrDays = Date.CultureInfo.abbreviatedDayNames.slice();
    this.arrMonth = this.language.monthNames;
    this.arrDays = this.language.abbreviatedDayNames;
        
    if (this.locale == 'ru' || this.locale == 'ua')
    {
      item = this.arrDays.shift();
      this.arrDays.push(item);
    }
  },
  
  // Stop current event
  stop_event: function(e)
  { 
    if (e && ((typeof(e) == "object")))
    {
      Event.stop(e);
    }
  },
  
  // Show calendar and start timeout for hide
  show: function()
  {
  	this.element.style.display = '';
	  this.show_mode = true;
	
	  this.setTimeMode(1);
	
	  //start event to hide calendar
	  this.startTimeout();
	  
	  if(typeof(this.options.onShow) == 'function') this.options.onShow(this);
  },
  
  // Hide calendar
  hide: function(event)
  {
	  this.element.style.display = 'none';
	  this.show_mode = false;
	  
	  this.stopTimeout();
	  
	  this.stop_event(event);
	  
	  if(typeof(this.options.onHide) == 'function') this.options.onHide(this);
  },
  
  // Hide or Show calendar
  toggle: function()
  {
    this.show_mode ? this.hide() : this.show();
  },
  
  getDate: function()
  {
	  return new Date(this.sYear, this.sMonth, this.sDay, this.sHour, this.sMinute);
  },
  
  setDate: function(date)
  {
	  this.sYear = date.getFullYear();
	  this.sMonth = this.mMonth = date.getMonth();
	  this.sDay = this.mDay = date.getDate();
	
	  this.sHour = date.getHours();
	  this.sMinute = date.getMinutes();
	
	  this.fYear = this.sYear - 5;
	  this.mYear = this.sYear;
	
	  this.initYearList(this.fYear);
	  this.initMonthList(this.sMonth);
	  this.initDate();
	  this.initTime();
  },
  
  // Call setYear from event
  setYearEvent: function(event)
  {
    var a = Event.element(event);
    this.setYear(a.title);
    
    this.stop_event(event);
  },
  
  // Set year
  setYear: function(year)
  {
  	this.mYear = year;
	  this.initYearList(this.fYear);
	
	  this.initDate();
  },
  
  // Event for month link click
  setMonthEvent: function(event)
  {
    var link = Event.element(event);
    var month = parseInt(link.id.replace('c_month_', ''));
    
    this.setMonth(month);
    this.stop_event(event);
  },
  
  // Set month
  setMonth: function(month)
  {
	  this.mMonth = month;
	  this.initMonthList(month);
	
	  this.initDate();
  },
  
  // Day calendar click event
  setDayEvent: function(event)
  {
    var link = Event.element(event);
    var items = link.id.split('_');
    
    this.setDay(items[0], items[1]);
    
    this.stop_event(event);
  },
  
  // Select day
  setDay: function(day, month)
  {
	  this.sYear = this.mYear;
  	this.sDay = day;
	  this.sMonth = month;
	
	  this.initDate();
	
	  //if(typeof(this.options.onSelect) == 'function') this.options.onSelect.call(this.options.onSelectParams);
  },
  
  // Event for select calendar link click
  select: function(event)
  {
  	if(typeof(this.options.onSelect) == 'function') this.options.onSelect(this);
	  
	  this.stop_event(event);
  },
  
  // Fill calendar days
  initDate: function()
  {
	  //var month = (this.mMonth % 2) ? this.mMonth - 1 : this.mMonth;
	  var month = (this.mMonth == 11) ? this.mMonth - 1 : this.mMonth;
	
	  this.populateCalendar(this.mDay, month, this.mYear, this.element_day_list_1);
	  this.populateCalendar(this.mDay, month + 1, this.mYear, this.element_day_list_2);
  },
  
  // Event for year button next click
  moveYearListUp: function(event)
  {
	  this.fYear += 1;
	  this.initYearList(this.fYear);
	  
	  this.stop_event(event);
  },
  
  // Event for year button prev click
  moveYearListDown: function(event)
  {
	  this.fYear -= 1;
  	this.initYearList(this.fYear);
  	
  	this.stop_event(event);
  },
  
  // Create and fill years list
  initYearList: function(year) 
  {
    var i_year = null;
    var a = null;
    
    this.element_year_list.innerHTML = '';
    
    for(var i = 0; i < 11; i++)
    {
  		i_year = (year + i);
  		
  		a = document.createElement('A');
  		a.href = 'javascript:void(0);';
	    a.title = i_year;
	    a.innerHTML = i_year;
	  		
	  	if (i_year == this.mYear)
	  	{
	  		a.className = 'actyer';
	  	}
	  	else
	  	{
	  	  Event.observe(a, 'click', this.setYearEvent.bind(this));
	  	}
	  	
	  	this.element_year_list.appendChild(a);
    }
  },
  
  // Create and fill month list
  initMonthList: function(month)
  {
  	var last_link = null;
	  var className = null;
	  //var s_month = (this.mMonth % 2) ? this.mMonth - 1 : this.mMonth + 1;
	  var s_month = (this.mMonth == 11) ? this.mMonth - 1 : this.mMonth + 1;
	  var a = null;
    
  	this.element_month_list.innerHTML = '';
      		  
	  for(var i = 0; i < this.arrMonth.length; i++)
	  {
		  className = ((i == this.mMonth) || (i == s_month)) ? 'actmonth' : '';
		  
		  a = document.createElement('A');
		  a.href = 'javascript:void(0);';
		  a.id = "c_month_" + i;
		  a.className = className;
		  a.innerHTML = this.arrMonth[i];
		  a.title = this.arrMonth[i];
		  
		  Event.observe(a, 'mouseout', this.mouseOutEvent.bind(this));
		  Event.observe(a, 'mouseover', this.mouseOverEvent.bind(this));
		  Event.observe(a, 'click', this.setMonthEvent.bind(this));
		  
      this.element_month_list.appendChild(a);
	  }
  },
  
  // Create and fill days names list
  initDaysNames: function()
  {
    var tbody = this.element_days_names.tBodies[0];
    var className = null;
    
    while (tbody.rows.length > 0){ tbody.deleteRow(0); };
    
    var row = tbody.insertRow(0);
    var cell = null;
    
    for(var i = 0; i < this.arrDays.length; i++)
	  {
		  className = ((i == 5) || (i == 6)) ? 'cell_red' : '';
		  
		  cell = row.insertCell(row.cells.length);
		  cell.className = className;
		  cell.innerHTML = this.arrDays[i];
		}
  },
  
  // Event for time mode link click
  setTimeModeEvent: function(event)
  {
    var element = Event.element(event);
    var param = (element == this.element_hour ? 1 : 0)
    
    this.setTimeMode(param)
    this.stopTimeout();
    
    this.stop_event(event);
  },
  
  // Set time mode: 1 - hours, 0 - minutes
  setTimeMode: function(param)
  {
    this.time_mode = (param == 1);
	  if(this.time_mode)
	  {
		  this.element_hour.className = "act";
		  this.element_minute.className = "";
	  }
	  else
	  {
		  this.element_hour.className = "";
		  this.element_minute.className = "act";
	  }
  },
  
  // Incriment time list
  moveTimeListUp: function()
  {
	  if (this.time_mode)
	  {
		  this.sHour = parseInt(this.sHour, 10);
		  if (this.sHour == 23)
		  {
			  this.sHour = 0;
		  }
		  else
		  {
			  this.sHour += 1;
		  }
	  }
	  else
	  {
		  this.sMinute = parseInt(this.sMinute, 10);
		  if (this.sMinute == 59)
		  {
			  this.sMinute = 0;
		  }
		  else
		  {
			  this.sMinute += 1;
		  }
	  }
	
	  this.initTime();
  },
  
  // Decriment time list
  moveTimeListDown: function()
  {
	  if (this.time_mode)
	  {
		  this.sHour = parseInt(this.sHour, 10);
		  if (this.sHour == 0)
		  {
			  this.sHour = 23;
		  }
		  else
		  {
			  this.sHour -= 1;
		  }
	  }
	  else
	  {
		  this.sMinute = parseInt(this.sMinute, 10);
		  if (this.sMinute == 0)
		  {
			  this.sMinute = 59;
		  }
		  else
		  {
			  this.sMinute -= 1;
		  }
	  }
	
	  this.initTime();
  },
  
  // Event for time prev link click
  startTimerEvent: function(event)
  {
    var element = Event.findElement(event, 'A');
    var func = (element == this.time_link_prev ? 1 : 0);
    
    if (func == 1)
	  {
	    this.moveTimeListUp();
	    this.time_out = window.setTimeout(this.startTimerUp.bind(this), 200);  
	  }
	  else
	  {
	    this.moveTimeListDown();
	    this.time_out = window.setTimeout(this.startTimerDown.bind(this), 200);
	  }
    
    this.eventEndTimer = this.endTimer.bindAsEventListener(this);
	  Event.observe(document, "mouseup", this.eventEndTimer);
  },
  
  // Start timer for incriment time select
  startTimerUp: function()
  {
	  window.clearTimeout(this.time_out);
	  
	  this.moveTimeListUp();
	  
	  this.time_out = window.setTimeout(this.startTimerUp.bind(this), 200);
  },
  
  // Start timer for decriment time select
  startTimerDown: function()
  {
	  window.clearTimeout(this.time_out);
	  
	  this.moveTimeListDown();
	  
	  this.time_out = window.setTimeout(this.startTimerDown.bind(this), 200);
  },
  
  // Stop timer for time prev link click
  endTimer: function(event)
  {
	  window.clearTimeout(this.time_out);
	  
  	Event.stopObserving(document, "mouseup", this.eventEndTimer);
  	
  	this.stop_event(event);
  },
  
  // Create and fill time content
  initTime: function()
  {
	  var str1 = (this.sMinute >= 10) ? this.sMinute : "0" + this.sMinute;
	  var str2 = (this.sHour >= 10) ? this.sHour : "0" + this.sHour;
	
	  this.element_minute.innerHTML = str1;
	  this.element_hour.innerHTML = str2;
  },
  
  // Reset time in 00:00 or 23:59 if time_reset is false
  resetTime: function()
  {
	  if (this.time_reset)
	  {
		  this.sHour = 0;
		  this.sMinute = 0;
	  }
	  else
	  {
		  this.sHour = 23;
		  this.sMinute = 59;
	  }
	
	  this.initTime();
  },
  
  keypress: function(evt)
  {
	  if(this.show_mode)
	  {
		  evt = (evt) ? evt : ((window.event) ? event : null);
		  var elem = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
		  if (evt) 
		  {	//alert(evt.keyCode);
			  // for Ctrl+Alt+F2
			  //if (evt.keyCode == 113 && evt.ctrlKey && evt.altKey)
			
			  var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
			  if(evt.keyCode == 9) //tab
			  {
				  this.time_mode = !this.time_mode;
				  this.setTimeMode(this.time_mode ? 1 : 0);
			  }
			  if(evt.keyCode == 13) //enter
			  {
				  this.select();
			  }
			  if ((charCode >= 48 && charCode <= 57)) //(charCode >= 96 && charCode <= 105)
			  {
				  //alert(String.fromCharCode(charCode));
				  var value = String.fromCharCode(charCode);
				  if (this.time_mode)
				  {
					  if (this.sHour > 0 && this.sHour <= 2)
					  {
						  if (this.sHour == 2)
						  {
							  if (value >= 0 && value <=3)
							  {
								  this.sHour += value;
							  }
						  }
						  else
						  {
							  this.sHour += value;
						  }
					  }
					  else
					  {
						  this.sHour = value;
					  }
				  }
				  else
				  {
					  if (this.sMinute > 0 && this.sMinute <= 5)
					  {
						  this.sMinute += value;
					  }
					  else
					  {
						  this.sMinute = value;
					  }
				  }
				
				  this.initTime();
			  }
		  }
    }
  },
  
  // Event for month link over
  mouseOverEvent: function(event)
  {
    var link = Event.element(event);
    var month = parseInt(link.id.replace('c_month_', ''));
    
    this.mouseOver(link, month);
    this.stopTimeout();
    
    this.stop_event(event);
  },
  
  // HightLight month on over
  mouseOver: function(link, month)
  {
	  var s_month = (month == 11) ? month - 1 : month + 1;
	  var nlink = $('c_month_' + s_month); // next link
	  
	  if (nlink.className != 'actmonth') nlink.className = 'hover';
	  if(link.className != 'actmonth') link.className = 'hover';
  },
  
  // Event for month link out
  mouseOutEvent: function(event)
  {
    var link = Event.element(event);
    var month = parseInt(link.id.replace('c_month_', ''));
    
    this.mouseOut(link, month);
    this.startTimeout();
    
    this.stop_event(event);
  },
  
  // HightLight month on out
  mouseOut: function(link, month)
  {
	  //var s_month = (month % 2) ? month - 1 : month + 1;
	  var s_month = (month == 11) ? month - 1 : month + 1;
    var nlink = $('c_month_' + s_month); // next link
    
	  if (link.className != 'actmonth') link.className = '';
	  if (nlink.className != 'actmonth') nlink.className = '';
  },
  
  // Fill two days lists
  populateCalendar: function(theDay, theMonth, theYear, tBody)
  {
    var firstDay = this.getFirstDay(theYear, theMonth);
    var howMany = this.getMonthLen(theYear, theMonth);
    var currDate = new Date(theYear, theMonth, theDay);
    var today = new Date();
    var dayCounter = 1;
    var newR, newC, dateNum;
    var done = false;
    var a = null;

    tBody.rows[0].cells[0].innerHTML = this.arrMonth[theMonth];
    
    while (tBody.rows.length > 1) { tBody.deleteRow(1); }

    while (!done) 
    {
        newR = tBody.insertRow(tBody.rows.length);
        if (newR) 
        {
            for (var i = 0; i < 7; i++) 
            {
                newC = newR.insertCell(newR.cells.length);
                
                if (tBody.rows.length == 2 && i < firstDay) 
                {
                    newC.innerHTML = "&nbsp;";
                    continue;
                }
                
                if (dayCounter == howMany) done = true;
                if(i == 5 || i == 6) newC.className = 'cell_red';
                
                if (dayCounter <= howMany) 
                {
                    a = document.createElement('A');
                    a.innerHTML = dayCounter;
                    a.title = dayCounter;
                    a.href = 'javascript:void(0)';
                    a.id = dayCounter + "_" + theMonth;
                    
                    if (today.getFullYear() == theYear && today.getMonth() == theMonth && today.getDate() == dayCounter)
                    {
                        newC.id = "today";
                    }
                    
                    if (this.sYear == theYear && this.sMonth == theMonth && this.sDay == dayCounter)
                    {
                       a.className = 'dataSelect';
                    }
                    else
                    {
                      Event.observe(a, 'click', this.setDayEvent.bind(this));
                    }
                    
                    newC.appendChild(a);
                    dayCounter++;
               } 
               else 
               {
                  newC.innerHTML = "&nbsp;";
               }
            }
        } 
        else 
        {
            done = true;
        }
    }
  },
  
  // Get first day of month
  getFirstDay: function (year, month)
  {
	  var firstDate = new Date(year, month, 1);
	  var day = firstDate.getDay();
	  
	  if (day == 0) return 6;
	  
	  return day - 1;
  },
  
  // Get count days in month
  getMonthLen: function (year, month) 
  {
    var nextMonth = new Date(year, month + 1, 1);    
    nextMonth.setHours(nextMonth.getHours() - 3);
    
    return nextMonth.getDate();
  },
  
  position_on: function(element)
  {
    var pos = Element.cumulativeOffset(element);
    var width = element.getWidth() + 5;
    //if(pos.top > 150) pos.top = pos.top - 150;
    
    this.setCalendarPosition(pos.left + width, pos.top);
  },
  
  // Set calendar position by left (x) and top (y) in px
  setCalendarPosition: function(x, y)
  {
	  this.element.style.left = x + 'px';
	  this.element.style.top = y + 'px';
  },
  
  // Stop timeout for hide calendar
  stopTimeout: function()
  {
	  if (document.body.getAttribute("HideCalendarTimeOut") !=null)
	  {
		  this.ClearTimeOut("HideCalendarTimeOut");
	  }
  },

  // Start timeout for hide calendar
  startTimeout: function()
  {
    if (this.options.timer)
    {
	    this.ClearTimeOut("HideCalendarTimeOut");
	    document.body.setAttribute("HideCalendarTimeOut", window.setTimeout(this.hide.bind(this), this.options.timeout));
	  }
	  else
	  {
	    return false;
	  }
  },
  
  // Clear timeouts by attribute
  ClearTimeOut:	function(oAttribute)
  {
	  var id = document.body.getAttribute(oAttribute);
	  if (id !=null)
	  {
		  window.clearTimeout(id);
	  }
	
	  document.body.removeAttribute(oAttribute);
  },
  
  // Parse date from string
  parseDate: function(value)
  {
    var arr = value.split(".");
    var day = parseInt(arr[0], 10);
    var month = parseInt(arr[1], 10);
    var year = parseInt(arr[2], 10);
    var hour = parseInt(arr[3], 10);
    var minute = parseInt(arr[4], 10);
    var date = new Date(year, month - 1, day, hour, minute);
    
    this.setDate(date);
  },
  
  // Return date in format
  format_date: function(format)
  {
    var date = this.getDate();
    
    if (typeof(format) == "undefined") format = this.options.format;
    return date.format(format);
  }
}

function selectDate(calendar)
{ 
	var element_id = calendar.element.id;
	var hidden = $(element_id + '_hidden');
	var text = $(element_id + '_text');
	
	calendar.hide();
	
	hidden.value = calendar.format_date("%d.%m.%Y.%H.%M");
	text.innerHTML = calendar.format_date();
}

function showCalendar(event, calendar)
{ 
  var element = Event.findElement(event, 'A');
  var element_id = calendar.element.id;
  var hidden = $(element_id + '_hidden');
	
	if (typeof(calendar) == 'undefined' || calendar == null) return;
	if (hidden) calendar.parseDate(hidden.value);  
  calendar.time_reset = 1;
	calendar.position_on(element);
	calendar.toggle();
	
	Event.stop(event);
}
